package com.suray.basic.wcs.plc.pojo.device;

import com.suray.basic.wcs.utils.Coord;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.socket.SocketInterface;
import com.suray.socket.core.SocketInstance;
import com.suray.socket.type.SocketType;

import java.io.IOException;

/**
 * 扫码器
 *
 * @date 2022-6-16
 * @author mj
 */
public class Scanner {
    private SocketInterface comm;
    private String scanName;

    private String deviceNo;
    private Coord location;
    private boolean enable;

    private String barcode;

    private final String startCmd = "START";
    private final String endCmd = "STOP";

    public Scanner(String name, String deviceNo, String ip, int port, Coord coord, boolean enable) {
        this.scanName = name;
        this.deviceNo = deviceNo;
        this.location = coord;
        this.enable = enable;

        comm = SocketInstance.getInstance(ip, port, SocketType.CLIENT);
    }

    public String getDeviceNo() {
        return deviceNo;
    }

    public Coord getLocation() {
        return location;
    }

    public boolean isEnable() {
        return enable;
    }

    public String getScanName() {
        return scanName;
    }

    /**
     * 开启扫码器
     * @throws IOException
     */
    public void startScan() throws IOException {
        comm.sendData(startCmd.getBytes());
    }

    /**
     * 关闭扫码器
     * @throws IOException
     */
    public void stopScan() throws IOException {
        comm.sendData(endCmd.getBytes());
    }

    /**
     * 关闭扫码器，并读取扫码结果
     * @throws IOException
     */
    public void endScan() throws IOException {
        LoggerUtil.info("扫码结果", this.getClass());
        stopScan();
        byte[] recData = recScan(5);
        if (recData == null) {
            LoggerUtil.info("扫码结果为空", this.getClass());
        }
        String recStr = new String(recData);
        LoggerUtil.info(getScanName() + "读取到数据：" + recStr, this.getClass());
        String[] strs = recStr.split("\n");
        barcode = strs[2].replace("\r", "");
    }

    /**
     * 条码是否可读
     * @return
     */
    public boolean isCanRead() {
        return barcode == null;
    }

    /**
     * 读取条码
     * @return
     */
    public String getBarcode() {
        return barcode;
    }

    /**
     * 清除扫码数据
     */
    public void clearScan() {
        try {
            barcode = null;
            stopScan();
            comm.recData(500);
        } catch (IOException e) {
        }
    }

    /**
     * 读取条码
     * @param count
     * @return
     * @throws IOException
     */
    public byte[] recScan(int count) throws IOException {
        try {
            return comm.recData(200);
        } catch (IOException e) {
            if (count > 0) {
                return recScan(--count);
            } else {
                LoggerUtil.error(scanName + "扫码器读取条码失败！", this.getClass());
                throw e;
            }
        }
    }
}
